package com.naton.common.network

import androidx.annotation.Nullable
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.HashMap
import java.util.concurrent.TimeUnit

abstract class BaseRetrofitClient {


    companion object CLIENT {
        private const val TIME_OUT = 20
        private const val LOG_LEVEL = 1
    }

    /*okhttp客户端*/
    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(getPublicParamsInterceptor())
        .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
        .build()

    /**
     * 获取公共参数拦截器
     */
    private fun getPublicParamsInterceptor() : Interceptor {
        return object : AddParameterInterceptor() {
            override fun getPubParamsMap(): HashMap<String, String> {
                return getMyPubParamsMap()
            }
        }
    }

    /**
     * 获取公共参数
     */
    abstract fun getMyPubParamsMap(): HashMap<String, String>

    /**
     * 获取先关接口服务
     */
    open fun <Service> getService(
        serviceClass: Class<Service>,
        @Nullable baseUrl: String
    ): Service {
        return Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(baseUrl)
            .build()
            .create(serviceClass)
    }
}